<template>
  <!-- 前面的模板内容保持不变 -->
  <div class="reports-container">
    <div class="page-header">
      <div class="page-title">
        <h2>诊断报告管理</h2>
      </div>
      <div class="page-actions">
        <a-button type="primary" @click="showNewReportModal">
          <template #icon><plus-outlined /></template>
          新建报告
        </a-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="关键词">
          <a-input v-model:value="searchForm.keyword" placeholder="患者姓名/报告编号" allowClear />
        </a-form-item>
        <a-form-item label="报告类型">
          <a-select v-model:value="searchForm.type" placeholder="请选择" style="width: 120px" allowClear>
            <a-select-option value="initial">初诊报告</a-select-option>
            <a-select-option value="progress">复诊报告</a-select-option>
            <a-select-option value="final">治疗总结</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="创建日期">
          <a-range-picker v-model:value="searchForm.dateRange" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        :scroll="{ x: 1200 }"
      >
        <!-- 使用自定义插槽渲染表格单元格 -->
        <template #bodyCell="{ column, record }">
          <!-- 报告类型列 -->
          <template v-if="column.dataIndex === 'type'">
            <a-tag :color="getTypeColor(record.type)">{{ getTypeText(record.type) }}</a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" @click="viewReport(record)">查看</a-button>
              <a-button type="link" @click="editReport(record)">编辑</a-button>
              <a-button type="link" @click="previewPrint(record)">打印</a-button>
              <a-popconfirm
                title="确定要删除这条报告吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteReport(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新建/编辑报告弹窗 -->
    <a-modal
      v-model:visible="reportModalVisible"
      :title="modalTitle"
      width="800px"
      @ok="formRef?.validate().then(handleReportSubmit)"
      :confirmLoading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="reportForm"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="template" label="报告模板">
              <a-select v-model:value="reportForm.template" placeholder="请选择报告模板">
                <a-select-option value="standard">标准诊断报告</a-select-option>
                <a-select-option value="detailed">详细诊断报告</a-select-option>
                <a-select-option value="summary">治疗总结报告</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="patientName" label="患者姓名">
              <a-input v-model:value="reportForm.patientName" placeholder="请输入患者姓名" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="type" label="报告类型">
              <a-select v-model:value="reportForm.type" placeholder="请选择报告类型">
                <a-select-option value="initial">初诊报告</a-select-option>
                <a-select-option value="progress">复诊报告</a-select-option>
                <a-select-option value="final">治疗总结</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="doctor" label="诊断医生">
              <a-input v-model:value="reportForm.doctor" placeholder="请输入诊断医生姓名" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item name="diagnosis" label="诊断结果">
          <a-textarea v-model:value="reportForm.diagnosis" placeholder="请输入诊断结果" :rows="4" />
        </a-form-item>
        
        <a-form-item name="treatment" label="治疗方案">
          <a-textarea v-model:value="reportForm.treatment" placeholder="请输入治疗方案" :rows="4" />
        </a-form-item>
        
        <a-form-item name="images" label="相关影像资料">
          <a-upload
            v-model:fileList="reportForm.images"
            list-type="picture-card"
            :action="uploadAction"
            :before-upload="beforeUpload"
            @preview="handleImagePreview"
          >
            <div v-if="reportForm.images.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        
        <a-form-item name="notes" label="备注">
          <a-textarea v-model:value="reportForm.notes" placeholder="请输入备注信息" :rows="3" />
        </a-form-item>
      </a-form>
      
      <!-- 图片预览 -->
      <a-modal
        v-model:visible="previewVisible"
        :footer="null"
        @cancel="handlePreviewVisibleChange(false)"
      >
        <img alt="预览图片" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-modal>

    <!-- 查看报告弹窗 -->
    <a-modal
      v-model:visible="viewModalVisible"
      title="查看报告"
      width="800px"
      :footer="[
        { key: 'print', text: '打印报告', type: 'primary', onClick: () => previewPrint(currentReport) },
        { key: 'close', text: '关闭', onClick: () => viewModalVisible = false }
      ]"
    >
      <div class="report-view" v-if="currentReport">
        <div class="report-header">
          <h2>{{ getTypeText(currentReport.type) }}</h2>
          <div class="report-info">
            <p><strong>报告编号：</strong>{{ currentReport.id }}</p>
            <p><strong>患者姓名：</strong>{{ currentReport.patientName }}</p>
            <p><strong>诊断医生：</strong>{{ currentReport.doctor }}</p>
            <p><strong>创建时间：</strong>{{ currentReport.createTime }}</p>
          </div>
        </div>
        
        <div class="report-section">
          <h3>诊断结果</h3>
          <p>{{ currentReport.diagnosis }}</p>
        </div>
        
        <div class="report-section">
          <h3>治疗方案</h3>
          <p>{{ currentReport.treatment }}</p>
        </div>
        
        <div class="report-section" v-if="currentReport.images && currentReport.images.length > 0">
          <h3>相关影像资料</h3>
          <div class="report-images">
            <div v-for="(image, index) in currentReport.images" :key="index" class="image-item">
              <img :src="image.url" :alt="`影像资料${index + 1}`" @click="handleImagePreview(image)" />
            </div>
          </div>
        </div>
        
        <div class="report-section" v-if="currentReport.notes">
          <h3>备注</h3>
          <p>{{ currentReport.notes }}</p>
        </div>
      </div>
    </a-modal>

    <!-- 打印预览弹窗 -->
    <a-modal
      v-model:visible="printPreviewVisible"
      title="打印预览"
      width="800px"
      :footer="[
        { key: 'print', text: '打印', type: 'primary', onClick: handlePrint },
        { key: 'cancel', text: '取消', onClick: () => printPreviewVisible = false }
      ]"
    >
      <div id="printContent" ref="printContent">
        <div class="print-report">
          <div class="print-header">
            <h1>牙科诊断报告</h1>
            <div class="print-info">
              <p><strong>报告编号：</strong>{{ currentReport?.id }}</p>
              <p><strong>患者姓名：</strong>{{ currentReport?.patientName }}</p>
              <p><strong>报告类型：</strong>{{ getTypeText(currentReport?.type) }}</p>
              <p><strong>诊断医生：</strong>{{ currentReport?.doctor }}</p>
              <p><strong>创建时间：</strong>{{ currentReport?.createTime }}</p>
            </div>
          </div>
          
          <div class="print-section">
            <h2>诊断结果</h2>
            <p>{{ currentReport?.diagnosis }}</p>
          </div>
          
          <div class="print-section">
            <h2>治疗方案</h2>
            <p>{{ currentReport?.treatment }}</p>
          </div>
          
          <div class="print-section" v-if="currentReport?.notes">
            <h2>备注</h2>
            <p>{{ currentReport?.notes }}</p>
          </div>
          
          <div class="print-footer">
            <p>此报告由系统生成，如有疑问请咨询相关医生。</p>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { 
  UserOutlined,
  PlusOutlined,
  SearchOutlined,
  FileTextOutlined,
  PrinterOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

// 表单引用
const formRef = ref(null)
const submitLoading = ref(false)
const previewImage = ref('')
const uploadAction = 'https://www.mocky.io/v2/5cc8019d300000980a055e76' // 模拟上传地址

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
  type: '',
  dateRange: null
})

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.type = ''
  searchForm.dateRange = null
  handleSearch()
}

// 表格列定义
const columns = [
  {
    title: '报告编号',
    dataIndex: 'id',
    key: 'id',
    width: 120
  },
  {
    title: '患者姓名',
    dataIndex: 'patientName',
    key: 'patientName',
    width: 120
  },
  {
    title: '报告类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '诊断医生',
    dataIndex: 'doctor',
    key: 'doctor',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    fixed: 'right',
    width: 200
  }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
})

// 报告弹窗相关
const reportModalVisible = ref(false)
const viewModalVisible = ref(false)
const printPreviewVisible = ref(false)
const modalTitle = ref('新建报告')
const currentReport = ref(null)
const printContent = ref(null)

// 图片预览相关
const previewVisible = ref(false)
const previewImages = ref([])

// 报告表单数据
const reportForm = reactive({
  template: '',
  patientName: '',
  type: '',
  doctor: '',
  diagnosis: '',
  treatment: '',
  images: [],
  notes: ''
})

// 表单验证规则
const rules = {
  template: [
    { required: true, message: '请选择报告模板', trigger: 'change' }
  ],
  patientName: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择报告类型', trigger: 'change' }
  ],
  doctor: [
    { required: true, message: '请输入诊断医生姓名', trigger: 'blur' }
  ],
  diagnosis: [
    { required: true, message: '请输入诊断结果', trigger: 'blur' }
  ],
  treatment: [
    { required: true, message: '请输入治疗方案', trigger: 'blur' }
  ]
}

// 获取报告类型颜色
const getTypeColor = (type) => {
  const colorMap = {
    initial: 'blue',
    progress: 'orange',
    final: 'green'
  }
  return colorMap[type] || 'default'
}

// 获取报告类型文本
const getTypeText = (type) => {
  const textMap = {
    initial: '初诊报告',
    progress: '复诊报告',
    final: '治疗总结'
  }
  return textMap[type] || '未知'
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchTableData()
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTableData()
}

// 获取表格数据
const fetchTableData = () => {
  loading.value = true
  // 模拟接口调用
  setTimeout(() => {
    // 模拟数据
    const mockData = [
      {
        id: 'R20240115001',
        patientName: '张三',
        type: 'initial',
        doctor: '李医生',
        createTime: '2024-01-15 10:00:00',
        diagnosis: '牙齿轻度错颌，需要进行正畸治疗评估。患者上颌前牙轻度拥挤，下颌牙齿排列基本正常。',
        treatment: '建议使用隐形矫正器进行为期18个月的正畸治疗，每两周更换一次矫正器，定期复诊检查进度。',
        notes: '患者对治疗方案表示认可，希望尽快开始治疗。',
        images: [
          {
            uid: '1',
            name: 'image1.jpg',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          }
        ]
      },
      {
        id: 'R20240120002',
        patientName: '李四',
        type: 'progress',
        doctor: '王医生',
        createTime: '2024-01-20 14:30:00',
        diagnosis: '牙齿矫正进展良好，上颌前牙拥挤情况有所改善。',
        treatment: '继续使用隐形矫正器，按计划更换，注意口腔卫生。',
        notes: '患者反映佩戴矫正器后有轻微不适，建议适应期过后再评估。',
        images: [
          {
            uid: '2',
            name: 'image2.jpg',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          }
        ]
      },
      {
        id: 'R20240205003',
        patientName: '王五',
        type: 'final',
        doctor: '张医生',
        createTime: '2024-02-05 09:15:00',
        diagnosis: '牙齿矫正治疗已完成，牙齿排列整齐，咬合关系良好。',
        treatment: '佩戴保持器，定期复查，保持良好的口腔卫生习惯。',
        notes: '患者对治疗结果非常满意，建议继续定期检查。',
        images: [
          {
            uid: '3',
            name: 'image3.jpg',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          }
        ]
      },
      {
        id: 'R20240210004',
        patientName: '赵六',
        type: 'initial',
        doctor: '李医生',
        createTime: '2024-02-10 11:20:00',
        diagnosis: '上颌右侧第一磨牙龋齿，需要进行充填治疗。',
        treatment: '建议使用复合树脂材料进行充填，术后注意口腔卫生，减少甜食摄入。',
        notes: '患者对治疗方案表示理解，预约下周进行治疗。',
        images: [
          {
            uid: '4',
            name: 'image4.jpg',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          }
        ]
      },
      {
        id: 'R20240215005',
        patientName: '钱七',
        type: 'progress',
        doctor: '王医生',
        createTime: '2024-02-15 15:45:00',
        diagnosis: '牙齿美白治疗第二次复查，效果良好，色阶提升明显。',
        treatment: '继续使用家庭美白套装，每晚使用30分钟，避免摄入色素重的食物和饮料。',
        notes: '患者对治疗效果表示满意，将继续按计划进行。',
        images: [
          {
            uid: '5',
            name: 'image5.jpg',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          }
        ]
      }
    ]
    
    // 根据搜索条件过滤
    let filteredData = [...mockData]
    
    if (searchForm.keyword) {
      const keyword = searchForm.keyword.toLowerCase()
      filteredData = filteredData.filter(item => 
        item.patientName.toLowerCase().includes(keyword) || 
        item.id.toLowerCase().includes(keyword)
      )
    }
    
    if (searchForm.type) {
      filteredData = filteredData.filter(item => item.type === searchForm.type)
    }
    
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      // 这里应该有日期过滤逻辑，但由于是模拟数据，暂不实现
    }
    
    tableData.value = filteredData
    pagination.total = filteredData.length
    loading.value = false
    
    console.log('Loaded report data:', tableData.value)
  }, 500)
}

// 显示新建报告弹窗
const showNewReportModal = () => {
  modalTitle.value = '新建报告'
  Object.keys(reportForm).forEach(key => {
    reportForm[key] = key === 'images' ? [] : ''
  })
  reportModalVisible.value = true
}

// 查看报告
const viewReport = (record) => {
  console.log('Viewing report:', record)
  // 确保数据格式正确
  currentReport.value = { 
    ...record,
    // 确保images属性存在且为数组
    images: record.images || []
  }
  // 打开查看报告弹窗
  viewModalVisible.value = true
}

// 编辑报告
const editReport = (record) => {
  modalTitle.value = '编辑报告'
  Object.keys(reportForm).forEach(key => {
    reportForm[key] = record[key] || (key === 'images' ? [] : '')
  })
  reportModalVisible.value = true
}

// 打印预览
const previewPrint = (record) => {
  currentReport.value = { ...record }
  printPreviewVisible.value = true
}

// 处理打印
const handlePrint = () => {
  if (!printContent.value) return
  
  html2canvas(printContent.value).then(canvas => {
    const imgData = canvas.toDataURL('image/png')
    const pdf = new jsPDF('p', 'mm', 'a4')
    const pdfWidth = pdf.internal.pageSize.getWidth()
    const pdfHeight = pdf.internal.pageSize.getHeight()
    const imgWidth = canvas.width
    const imgHeight = canvas.height
    const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight)
    const imgX = (pdfWidth - imgWidth * ratio) / 2
    const imgY = 30
    
    pdf.addImage(imgData, 'PNG', imgX, imgY, imgWidth * ratio, imgHeight * ratio)
    pdf.save(`诊断报告_${currentReport.value.patientName}_${currentReport.value.id}.pdf`)
    
    message.success('报告已导出为PDF文件')
    printPreviewVisible.value = false
  })
}

// 处理图片预览
const handleImagePreview = (file) => {
  previewImage.value = file.url || file.preview
  previewVisible.value = true
}

// 处理预览窗口变化
const handlePreviewVisibleChange = (visible) => {
  previewVisible.value = visible
}

// 删除报告
const deleteReport = (record) => {
  // 模拟删除操作
  tableData.value = tableData.value.filter(item => item.id !== record.id)
  message.success('报告已删除')
}

// 上传前检查
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传JPG/PNG格式的图片!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!')
  }
  return isJpgOrPng && isLt2M
}

// 处理报告表单提交
const handleReportSubmit = () => {
  submitLoading.value = true
  
  // 模拟提交
  setTimeout(() => {
    // 生成唯一ID
    const id = modalTitle.value === '新建报告' 
      ? `R${new Date().getTime().toString().substr(3)}` 
      : reportForm.id
    
    const newReport = {
      id,
      patientName: reportForm.patientName,
      type: reportForm.type,
      doctor: reportForm.doctor,
      createTime: new Date().toLocaleString(),
      diagnosis: reportForm.diagnosis,
      treatment: reportForm.treatment,
      notes: reportForm.notes,
      images: reportForm.images
    }
    
    if (modalTitle.value === '新建报告') {
      // 新增
      tableData.value.unshift(newReport)
      message.success('报告创建成功')
    } else {
      // 编辑
      const index = tableData.value.findIndex(item => item.id === currentReport.value.id)
      if (index !== -1) {
        tableData.value[index] = newReport
      }
      message.success('报告更新成功')
    }
    
    reportModalVisible.value = false
    submitLoading.value = false
  }, 1000)
}

// 初始化加载数据
onMounted(() => {
  fetchTableData()
})
</script>

<style scoped>
.reports-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: #fff;
  padding: 16px 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  color: #1f1f1f;
}

.search-container {
  background: #fff;
  padding: 24px;
  margin-bottom: 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.table-container {
  background: #fff;
  padding: 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.danger-link {
  color: #ff4d4f;
}

.danger-link:hover {
  color: #ff7875;
}

/* 报告查看样式 */
.report-view {
  padding: 0 16px;
}

.report-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
  margin-bottom: 24px;
}

.report-header h2 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #1f1f1f;
  font-size: 20px;
}

.report-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.report-info p {
  margin: 0;
  line-height: 1.8;
}

.report-section {
  margin-bottom: 24px;
}

.report-section h3 {
  font-size: 16px;
  margin-bottom: 12px;
  color: #1f1f1f;
  font-weight: 500;
}

.report-section p {
  margin: 0;
  line-height: 1.6;
  color: #333;
}

.report-images {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 16px;
}

.image-item {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 打印报告样式 */
.print-report {
  padding: 24px;
  background: #fff;
  color: #333;
}

.print-header {
  text-align: center;
  margin-bottom: 36px;
  padding-bottom: 24px;
  border-bottom: 2px solid #1890ff;
}

.print-header h1 {
  margin: 0 0 24px 0;
  color: #1890ff;
  font-size: 24px;
}

.print-info {
  text-align: left;
  margin-top: 24px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.print-info p {
  margin: 0;
  line-height: 1.8;
}

.print-section {
  margin-bottom: 24px;
}

.print-section h2 {
  font-size: 18px;
  margin-bottom: 12px;
  color: #1890ff;
  font-weight: 500;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
}

.print-section p {
  margin: 0;
  line-height: 1.6;
}

.print-footer {
  margin-top: 48px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  text-align: center;
  color: #888;
  font-size: 12px;
}

@media (max-width: 768px) {
  .report-info,
  .print-info {
    grid-template-columns: 1fr;
  }
  
  .search-container .ant-form-item {
    margin-bottom: 16px;
  }
}
</style>